<<<<<<< HEAD
import axios from 'axios';


// 创建 axios 实例
const $http = axios.create({
  baseURL: "http://localhost:3000",   // 默认路由前缀
  timeout: 30000, // 设置超时时间
  // headers: {
  //   'Content-Type': 'application/json' // 设置默认请求头
  // }
});
=======
import axios from "axios"
// 这里封装axios  尽量不要动  除非写登录的需求

const service = axios.create({
    baseURL: "http://localhost:3000",
    timeout: 15000
})
>>>>>>> 8a6c8db17dcf7c89661036278fb63ab04194791d

// 添加请求拦截器
$http.interceptors.request.use((config) => {
  const accessToken = localStorage.getItem('accessToken');
  if (accessToken) {
    config.headers.authorization = "Bearer" + accessToken; // 添加 Bearer 前缀
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 刷新 Token 函数
async function refreshToken() {
  try {
    const response = await $http.post('/ybk/refresh', {
      // 可根据情况传递 refreshToken
      token: localStorage.getItem('refreshToken')
    });
    if (response.status === 200) {
      console.log(response.data.data.accessToken);
      
      localStorage.setItem('accessToken', response.data.data.accessToken);
      localStorage.setItem('refreshToken', response.data.data.refreshToken);
    }
    return response.data;
  } catch (error) {
    throw new Error("Token 刷新失败");
  }
}

let refreshing = false; // 标记是否正在刷新 Token
let queue = []; // 请求队列

// 添加响应拦截器
$http.interceptors.response.use((response) => {
  return response; // 直接返回响应数据
}, async (error) => {
  let { status,data,config } = error.response;
  if(refreshing){
    return new Promise((resolve)=>{
      queue.push({
        config,
        resolve
      })
    })
  }

  if(status === 401 && !config.url.includes('/ybk/refresh')){
    refreshing = true;
    const res = await refreshToken();
    refreshing = false;
    if(res.status === 200){
      queue.forEach(({config,resolve})=>{
        resolve($http(config))
      })
      return $http(config); // 重发请求
    }else{
      alert(data.msg || '登录已过期，请重新登录');
      return {}
    }
  }else{
    return error.response;
  }
});

export default $http;
